package eiisan.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入独占锁，实现线程安全都list简单例子
 * @author eii
 * @time 2020/10/18 2:43 下午
 */
public class ReentrantLockList {
    // 线程不安全都list
    private List<String> arrarys = new ArrayList<>();
    // 可重入独占锁
    private ReentrantLock lock = new ReentrantLock();

    public void add(String e){
        lock.lock();
        try {
            arrarys.add(e);
        } finally {
            lock.unlock();
        }
    }

    public void remove(String e){
        lock.lock();
        try {
            arrarys.remove(e);
        } finally {
            lock.unlock();
        }
    }

    public String get(int index){
        lock.lock();
        try {
            return arrarys.get(index);
        } finally {
            lock.unlock();
        }
    }

}
